﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 出库管理表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class OutboundmanagementService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Outboundmanagement> _outboundmanagementRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public OutboundmanagementService(SqlSugarRepository<Outboundmanagement> outboundmanagementRep, ISqlSugarClient sqlSugarClient)
    {
        _outboundmanagementRep = outboundmanagementRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询出库管理表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询出库管理表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<OutboundmanagementOutput>> Page(PageOutboundmanagementInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _outboundmanagementRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.outboundNumber.Contains(input.Keyword) || u.outboundType.Contains(input.Keyword) || u.consignee.Contains(input.Keyword) || u.consigneePhone.Contains(input.Keyword) || u.Desc.Contains(input.Keyword) || u.outboundGoods.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.outboundNumber), u => u.outboundNumber.Contains(input.outboundNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.outboundType), u => u.outboundType.Contains(input.outboundType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.consignee), u => u.consignee.Contains(input.consignee.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.consigneePhone), u => u.consigneePhone.Contains(input.consigneePhone.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Desc), u => u.Desc.Contains(input.Desc.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.outboundGoods), u => u.outboundGoods.Contains(input.outboundGoods.Trim()))
            .WhereIF(input.warehouseName != null, u => u.warehouseName == input.warehouseName)
            .WhereIF(input.outboundDateRange?.Length == 2, u => u.outboundDate >= input.outboundDateRange[0] && u.outboundDate <= input.outboundDateRange[1])
            .WhereIF(input.AssociatedNumber != null, u => u.AssociatedNumber == input.AssociatedNumber)
            .WhereIF(input.clientName != null, u => u.clientName == input.clientName)
            .WhereIF(input.Attn != null, u => u.Attn == input.Attn)
            .WhereIF(input.outboundNum != null, u => u.outboundNum == input.outboundNum)
            .WhereIF(input.manufactureNumberPeople != null, u => u.manufactureNumberPeople == input.manufactureNumberPeople)
            .WhereIF(input.DepartmentId != null, u => u.DepartmentId == input.DepartmentId)
            .WhereIF(input.manufactureNumberDateRange?.Length == 2, u => u.manufactureNumberDate >= input.manufactureNumberDateRange[0] && u.manufactureNumberDate <= input.manufactureNumberDateRange[1])
            .LeftJoin<WarehouseInfo>((u, warehouseName) => u.warehouseName == warehouseName.Id)
            .LeftJoin<Salesorders>((u, warehouseName, associatedNumber) => u.AssociatedNumber == associatedNumber.Id)
            .LeftJoin<Customers>((u, warehouseName, associatedNumber, clientName) => u.clientName == clientName.Id)
            .LeftJoin<UserInfo>((u, warehouseName, associatedNumber, clientName, attn) => u.Attn == attn.Id)
            .LeftJoin<UserInfo>((u, warehouseName, associatedNumber, clientName, attn, manufactureNumberPeople) => u.manufactureNumberPeople == manufactureNumberPeople.Id)
            .LeftJoin<department>((u, warehouseName, associatedNumber, clientName, attn, manufactureNumberPeople, department) => u.DepartmentId == department.Id)
            .Select((u, warehouseName, associatedNumber, clientName, attn, manufactureNumberPeople, department) => new OutboundmanagementOutput
            {
                Id = u.Id,
                outboundNumber = u.outboundNumber,
                outboundType = u.outboundType,
                warehouseName = u.warehouseName,
                warehouseNameFkDisplayName = $"{warehouseName.WarehouseName}",
                outboundDate = u.outboundDate,
                AssociatedNumber = u.AssociatedNumber,
                AssociatedNumberFkDisplayName = $"{associatedNumber.BillNumber}",
                clientName = u.clientName,
                clientNameFkDisplayName = $"{clientName.CustomerName}",
                consignee = u.consignee,
                consigneePhone = u.consigneePhone,
                Attn = u.Attn,
                AttnFkDisplayName = $"{attn.UserName}",
                Desc = u.Desc,
                Status = u.Status,
                outboundGoods = u.outboundGoods,
                outboundNum = u.outboundNum,
                outboundPrice = u.outboundPrice,
                manufactureNumberPeople = u.manufactureNumberPeople,
                manufactureNumberPeopleFkDisplayName = $"{manufactureNumberPeople.UserName}",
                DepartmentId = u.DepartmentId,
                DepartmentFkDisplayName = $"{department.DepartmentName}",
                manufactureNumberDate = u.manufactureNumberDate,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取出库管理表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取出库管理表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Outboundmanagement> Detail([FromQuery] QueryByIdOutboundmanagementInput input)
    {
        return await _outboundmanagementRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加出库管理表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加出库管理表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddOutboundmanagementInput input)
    {
        var entity = input.Adapt<Outboundmanagement>();
        return await _outboundmanagementRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新出库管理表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新出库管理表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateOutboundmanagementInput input)
    {
        var entity = input.Adapt<Outboundmanagement>();
        await _outboundmanagementRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除出库管理表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除出库管理表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteOutboundmanagementInput input)
    {
        var entity = await _outboundmanagementRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _outboundmanagementRep.FakeDeleteAsync(entity);   //假删除
        //await _outboundmanagementRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除出库管理表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除出库管理表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteOutboundmanagementInput> input)
    {
        var exp = Expressionable.Create<Outboundmanagement>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _outboundmanagementRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _outboundmanagementRep.FakeDeleteAsync(list);   //假删除
        //return await _outboundmanagementRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataOutboundmanagementInput input)
    {
        var warehouseNameData = await _outboundmanagementRep.Context.Queryable<WarehouseInfo>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.warehouseName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var associatedNumberData = await _outboundmanagementRep.Context.Queryable<Salesorders>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.AssociatedNumber)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BillNumber}"
            }).ToListAsync();
        var clientNameData = await _outboundmanagementRep.Context.Queryable<Customers>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.clientName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var attnData = await _outboundmanagementRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.Attn)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var manufactureNumberPeopleData = await _outboundmanagementRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.manufactureNumberPeople)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var departmentIdData = await _outboundmanagementRep.Context.Queryable<department>()
            .InnerJoinIF<Outboundmanagement>(input.FromPage, (u, r) => u.Id == r.DepartmentId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "warehouseName", warehouseNameData },
            { "associatedNumber", associatedNumberData },
            { "clientName", clientNameData },
            { "attn", attnData },
            { "manufactureNumberPeople", manufactureNumberPeopleData },
            { "departmentId", departmentIdData },
        };
    }
    
    /// <summary>
    /// 导出出库管理表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出出库管理表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageOutboundmanagementInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportOutboundmanagementOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "出库管理表导出记录");
    }
    
    /// <summary>
    /// 下载出库管理表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载出库管理表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportOutboundmanagementOutput>(), "出库管理表导入模板", (_, info) =>
        {
            if (nameof(ExportOutboundmanagementOutput.warehouseNameFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<WarehouseInfo>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportOutboundmanagementOutput.AssociatedNumberFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<Salesorders>().Select(u => $"{u.BillNumber}").Distinct().ToList();
            if (nameof(ExportOutboundmanagementOutput.clientNameFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<Customers>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportOutboundmanagementOutput.AttnFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportOutboundmanagementOutput.manufactureNumberPeopleFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportOutboundmanagementOutput.DepartmentFkDisplayName) == info.Name) return _outboundmanagementRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入出库管理表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入出库管理表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportOutboundmanagementInput, Outboundmanagement>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 仓库名称
                    var warehouseNameLabelList = pageItems.Where(x => x.warehouseNameFkDisplayName != null).Select(x => x.warehouseNameFkDisplayName).Distinct().ToList();
                    if (warehouseNameLabelList.Any()) {
                        var warehouseNameLinkMap = _outboundmanagementRep.Context.Queryable<WarehouseInfo>().Where(u => warehouseNameLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.warehouseName = warehouseNameLinkMap.GetValueOrDefault(e.warehouseNameFkDisplayName ?? "");
                            if (e.warehouseName == null) e.Error = "仓库名称链接失败";
                        });
                    }
                    // 链接 关联单号
                    var associatedNumberLabelList = pageItems.Where(x => x.AssociatedNumberFkDisplayName != null).Select(x => x.AssociatedNumberFkDisplayName).Distinct().ToList();
                    if (associatedNumberLabelList.Any()) {
                        var associatedNumberLinkMap = _outboundmanagementRep.Context.Queryable<Salesorders>().Where(u => associatedNumberLabelList.Contains($"{u.BillNumber}")).ToList().ToDictionary(u => $"{u.BillNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.AssociatedNumber = associatedNumberLinkMap.GetValueOrDefault(e.AssociatedNumberFkDisplayName ?? "");
                            if (e.AssociatedNumber == null) e.Error = "关联单号链接失败";
                        });
                    }
                    // 链接 客户名称
                    var clientNameLabelList = pageItems.Where(x => x.clientNameFkDisplayName != null).Select(x => x.clientNameFkDisplayName).Distinct().ToList();
                    if (clientNameLabelList.Any()) {
                        var clientNameLinkMap = _outboundmanagementRep.Context.Queryable<Customers>().Where(u => clientNameLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.clientName = clientNameLinkMap.GetValueOrDefault(e.clientNameFkDisplayName ?? "");
                            if (e.clientName == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnLabelList.Any()) {
                        var attnLinkMap = _outboundmanagementRep.Context.Queryable<UserInfo>().Where(u => attnLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Attn = attnLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.Attn == null) e.Error = "经办人链接失败";
                        });
                    }
                    // 链接 制单人
                    var manufactureNumberPeopleLabelList = pageItems.Where(x => x.manufactureNumberPeopleFkDisplayName != null).Select(x => x.manufactureNumberPeopleFkDisplayName).Distinct().ToList();
                    if (manufactureNumberPeopleLabelList.Any()) {
                        var manufactureNumberPeopleLinkMap = _outboundmanagementRep.Context.Queryable<UserInfo>().Where(u => manufactureNumberPeopleLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.manufactureNumberPeople = manufactureNumberPeopleLinkMap.GetValueOrDefault(e.manufactureNumberPeopleFkDisplayName ?? "");
                            if (e.manufactureNumberPeople == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentIdLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentIdLabelList.Any()) {
                        var departmentIdLinkMap = _outboundmanagementRep.Context.Queryable<department>().Where(u => departmentIdLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DepartmentId = departmentIdLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.DepartmentId == null) e.Error = "所在部门链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Outboundmanagement>>();
                    
                    var storageable = _outboundmanagementRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.outboundNumber?.Length > 32, "出库单号长度不能超过32个字符")
                        .SplitError(it => it.Item.outboundType?.Length > 32, "出库类型长度不能超过32个字符")
                        .SplitError(it => it.Item.consignee?.Length > 32, "收货人长度不能超过32个字符")
                        .SplitError(it => it.Item.consigneePhone?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.Desc?.Length > 300, "备注长度不能超过300个字符")
                        .SplitError(it => it.Item.outboundGoods?.Length > 32, "出库货品长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
